package jwt

import (
	"errors"
	"gin_project/config"
	"gin_project/utils/logs"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

var (
	jwtSignKey = []byte(config.JwtSignKey)
)

type MyCustomClaims struct {
	UserName string `json:"username"`
	jwt.RegisteredClaims
}

func GenToken(username string) (string, error) {

	// Create claims with multiple fields populated
	claims := MyCustomClaims{
		username,
		jwt.RegisteredClaims{
			// A usual scenario is to set the expiration time relative to the current time
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.JwtExpTime) * time.Minute)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "luotngli",
			Subject:   "lutong",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ss, err := token.SignedString(jwtSignKey)
	return ss, err
}

func ParseToken(ss string) (*MyCustomClaims, error) {
	token, err := jwt.ParseWithClaims(ss, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSignKey, nil
	})
	if err != nil {
		logs.Error(nil, "Token解析失败")
		return nil, err
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		//success则证明合法
		return claims, nil
	} else {
		logs.Warning(nil, "Token解析不合法")
		return nil, errors.New("Token不合法:invalid token")
	}
}
